// com/lailai/controller/RouterController.java
package com.lailai.controller;

import com.lailai.constant.ErrorCode;
import com.lailai.constant.HttpStatusCode;
import com.lailai.domainservice.response.SingleResponse;
import com.lailai.entity.Route;
import com.lailai.entity.vo.RouteVO;
import com.lailai.service.RouterService;
import com.lailai.service.impl.RouterServiceImpl;
import com.lailai.utils.RouteTreeUtil;
import jakarta.validation.Valid;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

import org.slf4j.Logger;

/**
 * 路由控制类
 *
 * @Author lgr
 * @Date 2025/6/27
 * @Wechat a983105834
 * @Email 983105834@qq.com
 * @Copyright <a href="www.lailai.ink">lailai个人空间</a>
 */
@RestController
@RequestMapping("/api")
public class RouterController {
    // 创建日志记录器
    private static final Logger logger = LoggerFactory.getLogger(RouterController.class);
    // 注入路由接口
    @Autowired
    private RouterService routerService;
    // 注入路由实现类以使用自定义方法
    @Autowired
    private RouterServiceImpl routerServiceImpl;

    /**
     * 获取扁平路由表数据
     *
     * @return 所有路由
     */
    @GetMapping("/getRoutes")
    public SingleResponse<List<RouteVO>> getRouterList() {
        try {
            // 使用自定义方法查询路由及其配置信息
            List<Route> routes = routerServiceImpl.listRoutesWithConfig();
            logger.info("从数据库查询到的路由: {}", routes);

            // 将 Route 实体列表转换为 RouteVO 列表
            List<RouteVO> routeVOs = routes.stream()
                    .map(RouteTreeUtil::convertToVO)
                    .collect(Collectors.toList());
            logger.info("转换后的RouteVO数量: {}", routeVOs.size());

            // 构建树形结构
            List<RouteVO> routeTree = RouteTreeUtil.buildRouteTree(routeVOs);
            logger.info("构建完成的路由树结构:{}", routeTree);
            return SingleResponse.of(routeTree);
        } catch (Exception e) {
            logger.error("【获取路由失败】", e);
            return SingleResponse.ofFailure(
                    String.valueOf(ErrorCode.SYSTEM_ERROR.getCode()),
                    "获取路由失败: " + e.getMessage()
            );
        }
    }

    @PostMapping("/addRoute")
    public SingleResponse<String> addRoute(@Valid @RequestBody RouteVO vo) {
        logger.info("【开始调用 addRoute】方法");
        try {
            // 1. 将 RouteVO 转换为 Route 实体
            Route route = RouteTreeUtil.convertToEntity(vo);

            // 2. 保存路由
            boolean resultSave = routerService.save(route);
            if (!resultSave) {
                return SingleResponse.ofFailure(
                        String.valueOf(ErrorCode.ROUTE_CONFIG_ERROR.getCode()),
                        "路由保存失败"
                );
            }

            return SingleResponse.of("添加成功");
        } catch (Exception e) {
            logger.error("【添加路由失败】错误详情:", e);
            return SingleResponse.ofFailure(
                    String.valueOf(ErrorCode.SYSTEM_ERROR.getCode()),
                    "添加路由失败: " + e.getMessage()
            );
        }
    }

    @DeleteMapping("/deleteRoute")
    public SingleResponse<String> deleteRoute(@RequestParam Integer id) {
        logger.info("【开始调用 deleteRoute】方法，接收到的 ID 为：{}", id);

        if (id == null) {
            logger.warn("【删除路由失败】ID 不能为空");
            return SingleResponse.ofFailure(
                    String.valueOf(ErrorCode.PARAMETER_ERROR.getCode()),
                    "ID不能为空"
            );
        }

        boolean result = routerService.removeById(id);
        if (result) {
            return SingleResponse.of("删除成功");
        } else {
            return SingleResponse.ofFailure(
                    String.valueOf(ErrorCode.ROUTE_NOT_FOUND.getCode()),
                    "路由不存在或删除失败"
            );
        }
    }

    @PutMapping("/updateRoute/id={id}")
    public SingleResponse<String> updateRoute(@PathVariable("id") Integer id, @RequestBody RouteVO route) {
        logger.info("【开始调用 updateRoute】方法");
        try {
            if (id == null) {
                return SingleResponse.ofFailure(
                        String.valueOf(ErrorCode.PARAMETER_ERROR.getCode()),
                        "ID不能为空"
                );
            }
            Route routeEntity = RouteTreeUtil.convertToEntity(route);
            logger.info("【接收到的路由数据】: {}", routeEntity);
            boolean result = routerService.updateById(routeEntity);
            if (!result) {
                return SingleResponse.ofFailure(
                        String.valueOf(ErrorCode.ROUTE_CONFIG_ERROR.getCode()),
                        "路由更新失败"
                );
            }
            return SingleResponse.of("更新成功");
        } catch (Exception e) {
            logger.error("【更新路由失败】错误详情:", e);
            return SingleResponse.ofFailure(
                    String.valueOf(ErrorCode.SYSTEM_ERROR.getCode()),
                    "更新路由失败: " + e.getMessage()
            );
        }
    }
}
